package com.soloyogame.anitoys.util.email;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.soloyogame.anitoys.util.PropertiesTool;

/**
 * SendCloud邮件发送公共类
 * @author 索罗游
 */
public class SendCloud 
{

	public static String convert(List<Mail> dataList) 
	{
		JSONObject ret = new JSONObject();
		JSONArray to = new JSONArray();
		JSONArray names = new JSONArray();
		JSONArray moneys = new JSONArray();
		JSONArray orderCodes = new JSONArray();
		JSONArray webNames = new JSONArray();
		JSONArray orderUrls = new JSONArray();
		JSONArray sendTimes = new JSONArray();
		JSONArray passwordUrls = new JSONArray();
		JSONArray productnames = new JSONArray();
		JSONArray daynums = new JSONArray();
		JSONArray vcodes = new JSONArray();
		
		for (Mail a : dataList) 
		{
			to.put(a.getReceiver());
			names.put(a.getReceiverName());
			orderCodes.put(a.getOrderCode());
			webNames.put(a.getWebName());
			orderUrls.put(a.getOrderUrl());
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
			sendTimes.put(format.format(a.getSendTime()));
			passwordUrls.put(a.getPasswordUrl());
			productnames.put(a.getProductName());
			daynums.put(a.getDaynum());
			vcodes.put(a.getVcode());
			moneys.put(a.money);
		}
		JSONObject sub = new JSONObject();
		sub.put("%name%", names);
		sub.put("%orderCode%", orderCodes);
		sub.put("%webname%", webNames);
		sub.put("%orderUrl%", orderUrls);
		sub.put("%sendTime%", sendTimes);
		sub.put("%money%", moneys);
		sub.put("%passwordUrl%", passwordUrls);
		sub.put("%productname%", productnames);
		sub.put("%daynum%", daynums);
		sub.put("%vcode%", vcodes);
		ret.put("to", to);
		ret.put("sub", sub);
		return ret.toString();
	}

	/**
	 * 普通的发送邮件
	 * @throws IOException
	 */
	public static void send_common() throws IOException 
	{
		final String url = "http://api.sendcloud.net/apiv2/mail/send";
		final String apiUser = "soloyo_test_wVSKNP";
		final String apiKey = "8LKKx7UYnqR3enn4";
		final String rcpt_to = "651701276@qq.com";

		String subject = "普通那个邮件主题";
		String html = "<html><head></head><body>"
				+ "<p>欢迎使用<a href='http://sendcloud.sohu.com'>SendCloud!</a></p></body></html>";

		HttpPost httpPost = new HttpPost(url);
		HttpClient httpClient = new DefaultHttpClient();

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiUser", apiUser));
		params.add(new BasicNameValuePair("apiKey", apiKey));
		params.add(new BasicNameValuePair("to", rcpt_to));
		params.add(new BasicNameValuePair("from", "sendcloud@sendcloud.org"));
		params.add(new BasicNameValuePair("fromname", "SendCloud"));
		params.add(new BasicNameValuePair("subject", subject));
		params.add(new BasicNameValuePair("html", html));

		httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

		HttpResponse response = httpClient.execute(httpPost);

		// 处理响应
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			// 正常返回, 解析返回数据
			System.out.println(EntityUtils.toString(response.getEntity()));
		} else {
			System.err.println("error");
		}
		httpPost.releaseConnection();
	}
	
	/**
	 * 普通的发送邮件
	 * @throws IOException
	 */
	public static boolean send_common(Mail mail) throws IOException 
	{
		final String url = mail.getUrl();
		final String apiUser = mail.getApiUser();
		final String apiKey = mail.getApiKey();
		final String rcpt_to = mail.getReceiver();
		List<Mail> dataList = new ArrayList<Mail>();
		dataList.add(mail);
		final String xsmtpapi = convert(dataList);
		String subject = mail.getSubject();
		String html = mail.getMessage();
		HttpPost httpPost = new HttpPost(url);
		HttpClient httpClient = new DefaultHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiUser", apiUser));
		params.add(new BasicNameValuePair("apiKey", apiKey));
		params.add(new BasicNameValuePair("to", rcpt_to));
		params.add(new BasicNameValuePair("from", mail.getSender()));
		params.add(new BasicNameValuePair("fromname", mail.getName()));
		params.add(new BasicNameValuePair("subject", subject));
		params.add(new BasicNameValuePair("html", html));
		params.add(new BasicNameValuePair("xsmtpapi", xsmtpapi));
		httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
		HttpResponse response = httpClient.execute(httpPost);
		// 处理响应
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
		{
			// 正常返回, 解析返回数据
			System.out.println(EntityUtils.toString(response.getEntity()));
			httpPost.releaseConnection();
			return true;
		} 
		else 
		{
			System.err.println("error");
			httpPost.releaseConnection();
			return false;
		}
	}


	public static void send_common_with_attachment()
			throws ClientProtocolException, IOException {

		final String url = "http://api.sendcloud.net/apiv2/mail/send";

		final String apiUser = "soloyo_test_wVSKNP";
		final String apiKey = "8LKKx7UYnqR3enn4";
		final String rcpt_to = "***";

		String subject = "...";
		String html = "...";

		HttpPost httpPost = new HttpPost(url);
		HttpClient httpClient = new DefaultHttpClient();

		// 涉及到附件上传, 需要使用 MultipartEntity
		MultipartEntity entity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE, null,
				Charset.forName("UTF-8"));
		entity.addPart("apiUser",
				new StringBody(apiUser, Charset.forName("UTF-8")));
		entity.addPart("apiKey",
				new StringBody(apiKey, Charset.forName("UTF-8")));
		entity.addPart("to", new StringBody(rcpt_to, Charset.forName("UTF-8")));
		entity.addPart("from", new StringBody("sendcloud@sendcloud.org",
				Charset.forName("UTF-8")));
		entity.addPart("fromname",
				new StringBody("SendCloud", Charset.forName("UTF-8")));
		entity.addPart("subject",
				new StringBody(subject, Charset.forName("UTF-8")));
		entity.addPart("html", new StringBody(html, Charset.forName("UTF-8")));

		// 添加附件
		File file = new File("D:\\1.txt");
		FileBody attachment = new FileBody(file, "application/octet-stream",
				"UTF-8");
		entity.addPart("attachments", attachment);

		// 添加附件, 文件流形式
		// File file = new File("D:\\1.txt");
		// String attachName = "attach.txt";
		// InputStreamBody is = new InputStreamBody(new FileInputStream(file),
		// attachName);
		// entity.addPart("attachments", is);

		httpPost.setEntity(entity);

		HttpResponse response = httpClient.execute(httpPost);
		// 处理响应
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			// 正常返回, 解析返回数据
			System.out.println(EntityUtils.toString(response.getEntity()));
		} else {
			System.err.println("error");
		}
		httpPost.releaseConnection();
	}

	/**
	 * 模版发送
	 * 
	 * @param dataList
	 *            邮件的数据集合
	 * @param subject
	 *            邮件的主题
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void send_template(List<Mail> dataList, String subject)
			throws ClientProtocolException, IOException {
		PropertiesTool props = new PropertiesTool("config.properties");
		final String url = props.getProperty("mailUrl");
		final String apiUser = props.getProperty("apiUser");
		final String apiKey = props.getProperty("apiKey");
		final String from = props.getProperty("from");
		final String fromname = props.getProperty("fromname");
		final String templateInvokeName = props
				.getProperty("templateInvokeName");
		final String xsmtpapi = convert(dataList);

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiUser", apiUser));
		params.add(new BasicNameValuePair("apiKey", apiKey));
		params.add(new BasicNameValuePair("xsmtpapi", xsmtpapi));
		params.add(new BasicNameValuePair("templateInvokeName",templateInvokeName));
		params.add(new BasicNameValuePair("from", from));
		params.add(new BasicNameValuePair("fromname", fromname));
		params.add(new BasicNameValuePair("subject", subject));

		httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

		HttpResponse response = httpClient.execute(httpPost);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
			System.out.println(EntityUtils.toString(response.getEntity()));
		} else {
			System.err.println("error");
		}
		httpPost.releaseConnection();
	}

	/**
	 * 模版发送
	 * @param mail
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static boolean send_template(Mail mail) throws ClientProtocolException,IOException 
	{
		List<Mail> dataList = new ArrayList<Mail>();
		dataList.add(mail);
		final String xsmtpapi = convert(dataList);

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(mail.getUrl());

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiUser", mail.getApiUser()));
		params.add(new BasicNameValuePair("apiKey", mail.getApiKey()));
		params.add(new BasicNameValuePair("xsmtpapi", xsmtpapi));
		params.add(new BasicNameValuePair("templateInvokeName",mail.getTemplateInvokeName()));
		params.add(new BasicNameValuePair("from", mail.getSender()));
		params.add(new BasicNameValuePair("fromname", mail.getName()));
		params.add(new BasicNameValuePair("subject", mail.getSubject()));

		httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

		HttpResponse response = httpClient.execute(httpPost);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
		{ 
			// 正常返回
			System.out.println(EntityUtils.toString(response.getEntity()));
			httpPost.releaseConnection();
			return true;
		} 
		else 
		{
			System.err.println("error");
			httpPost.releaseConnection();
			return false;
		}
		
	}

	public static void send_template_maillist() throws ClientProtocolException,
			IOException {

		final String url = "http://api.sendcloud.net/apiv2/mail/sendtemplate";

		final String apiUser = "soloyo_test_wVSKNP";
		final String apiKey = "8LKKx7UYnqR3enn4";
		// to is addressList
		final String to = "651701276@qq.com";

		String subject = "send_template_maillist测试";

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiUser", apiUser));
		params.add(new BasicNameValuePair("apiKey", apiKey));
		params.add(new BasicNameValuePair("to", to));
		params.add(new BasicNameValuePair("templateInvokeName", "test_template"));
		params.add(new BasicNameValuePair("from", "sendcloud@sendcloud.org"));
		params.add(new BasicNameValuePair("fromname", "SendCloud"));
		params.add(new BasicNameValuePair("subject", subject));
		params.add(new BasicNameValuePair("useAddressList", "true"));

		httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

		HttpResponse response = httpClient.execute(httpPost);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
			System.out.println(EntityUtils.toString(response.getEntity()));
		} else {
			System.err.println("error");
		}
		httpPost.releaseConnection();
	}

	public static void send_template_with_attachment()
			throws ClientProtocolException, IOException {
		final String url = "http://api.sendcloud.net/apiv2/mail/sendtemplate";
		final String apiUser = "soloyo_test_wVSKNP";
		final String apiKey = "8LKKx7UYnqR3enn4";

		String subject = "...";

		List<Mail> dataList = new ArrayList<Mail>();
		dataList.add(new Mail("651701276@qq.com", "user1", "1000"));
		dataList.add(new Mail("3114807004@qq.com", "user2", "2000"));

		final String xsmtpapi = convert(dataList);

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);

		// 涉及到附件上传, 需要使用 MultipartEntity
		MultipartEntity entity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE, null,
				Charset.forName("UTF-8"));
		entity.addPart("apiUser",
				new StringBody(apiUser, Charset.forName("UTF-8")));
		entity.addPart("apiKey",
				new StringBody(apiKey, Charset.forName("UTF-8")));
		entity.addPart("xsmtpapi",
				new StringBody(xsmtpapi, Charset.forName("UTF-8")));
		entity.addPart("templateInvokeName", new StringBody("test_template",
				Charset.forName("UTF-8")));
		entity.addPart("from", new StringBody("sendcloud@sendcloud.org",
				Charset.forName("UTF-8")));
		entity.addPart("fromname",
				new StringBody("SendCloud", Charset.forName("UTF-8")));
		entity.addPart("subject",
				new StringBody(subject, Charset.forName("UTF-8")));

		// 添加附件
		File file = new File("D://test/spy.log");
		FileBody attachment = new FileBody(file, "application/octet-stream",
				"UTF-8");
		entity.addPart("attachments", attachment);

		// 添加附件, 文件流形式
		// File file = new File("D:\\1.txt");
		// String attachName = "attach.txt";
		// InputStreamBody is = new InputStreamBody(new FileInputStream(file),
		// attachName);
		// entity.addPart("attachments", is);

		httpost.setEntity(entity);

		HttpResponse response = httpclient.execute(httpost);
		// 处理响应
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			// 正常返回, 解析返回数据
			System.out.println(EntityUtils.toString(response.getEntity()));
		} else {
			System.err.println("error");
		}
		httpost.releaseConnection();
	}

	public static void main(String[] args) throws Exception {
		 send_common();
		// send_common_with_attachment();
		// send_template_maillist();
		// send_template_with_attachment();
//		String subject = "模版发送";
//		List<Mail> dataList = new ArrayList<Mail>();
//		dataList.add(new Mail("651701276@qq.com", "user1", "1000"));
//		dataList.add(new Mail("3114807004@qq.com", "user2", "2000"));
//		send_template(dataList, subject);

	}
}
